
var remote = 'http://127.0.0.1:15151'
var user_server = 'http://user.hackerstack.top'


function auto_login() {

    try{
        var json = JSON.parse(document.cookie);
        var username =  json.user;
        var password = json.pwd;
        
        var xhr = new XMLHttpRequest();
        xhr.open("POST" ,user_server+ "/login",true);
        xhr.send(username+"\n"+password);
        
        xhr.onload=function(){
        // 返回的是 Json字符串，自己去处理,默认的信息是 {"message":"login successful."}
        var json_content = xhr.responseText;
        var json = JSON.parse(json_content);
        if (String(json.message).toLowerCase().includes("login successful.")) {
            document.cookie = "{\"user\" : \""+username+"\" , \"pwd\" : \""+password+"\"}";
            
            var login_btn = document.getElementById('login');
            login_btn.innerText = "登录: "+username;
            login_btn.onclick = function() {
                window.location.href = "./user.html";
            }
            var top = document.getElementById('a_top');
            top.className = 'top_btn'
            var exit_login = document.createElement('button');
            exit_login.className = 'b'
            exit_login.onclick=function() {
                document.cookie = '';
                window.location.href=''
            }
            exit_login.innerText = '退出登录'
            top.appendChild(exit_login);
            return true;
        } else {
            return false; 
        }
        }
    } catch(e) {
        document.cookie = '';
        document.cookie = "{\"user\" : \"\" , \"pwd\" : \"\"}";
        return false;
    }
}

window.onload=function(){
    auto_login();
    var url = window.location.href;
    var split_url = url.split("?");
    var map = new Map();
    for (var i = 0 ; i < split_url.length ;i++) {
        try{
            var split_value = split_url[i].split("=");
            map[split_value[0]] = split_value[1];
        }catch(e) {
            continue;
        }
    }
    var keyword = map['keyword'];
    var xhr = new XMLHttpRequest();
    xhr.open('GET' , remote+'/search/'+keyword , true)
    xhr.send();
    xhr.onload = function() {
        var search_content = document.getElementById('search_content');
        console.log(xhr.responseText)
        var json = JSON.parse(xhr.responseText)
        for (var i in json) {
            (function(id) {
                var btn = document.createElement('button');
                btn.className = 'search_object';
                btn.id = id;
                var j = Number(i)
                var a = j + 1;
                btn.innerText = a +'. '+id;
                btn.onclick=function() {
                    window.open('./player.html?music='+id);
                }
                search_content.appendChild(btn)
            }) (json[i])
        }
    }
}